#pragma
#include"Socket.hpp"
#include<signal.h>
#include"Log.hpp"
#include<functional>

//回调函数
using func_t=std::function<std::string(std::string& pack)>;


class TcpServer
{
public:
    TcpServer()
    {}
    bool Init()
    {
        listensockfd.Listen();
        listensockfd.Bind(port_);
        listensockfd.Socket();
        return true;
    }
    void Start()
    {
        while(true)
        {

            std::string clientip;
            uint16_t clientport;
            int sockfd=listensockfd.Accept(&clientip,&clientport);
            if(sockfd<0) continue;


            if(fork()==0)
            {
                listensockfd.Close();
                std::string inbuffer_stream;
                while(true)
                {
                    char inbuffer[128];
                    ssize_t n=read(sockfd,inbuffer,sizeof(inbuffer));
                    if(n>0)
                    {
                        inbuffer[n]=0;
                        inbuffer_stream+=inbuffer;
                        std::string ifo=callback_(inbuffer_stream);
                        if(ifo.empty()) break;

                        write(sockfd,&inbuffer,sizeof(inbuffer));
                    }   
                }
            }
        //提供服务
        close(sockfd);
        }


    }

private:
    uint16_t port_;//端口号
    Sock listensockfd;
    func_t callback_;
};